package com.xian.zk.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xian.zk.common.properties.ZookeeperProperties;
import com.xian.zk.core.DataServerUtil;
import com.xian.zk.model.ServerNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @program: zoo-task
 * @description:
 * @author: liru.xian
 * @create: 2022-01-14 16:41
 **/
@Slf4j
public class ServerNodeChildrenDateListener implements PathChildrenCacheListener {
    public static final String symbol  = "/";
    public static final ObjectMapper mapper = new ObjectMapper();

    private final CuratorFramework client;
    private final ZookeeperProperties zookeeperProperties;

    public ServerNodeChildrenDateListener(CuratorFramework client,ZookeeperProperties zookeeperProperties){
        this.client = client;
        this.zookeeperProperties = zookeeperProperties;
    }

    /**
     * Called when a change has occurred
     *
     * @param client the client
     * @param event  describes the change
     * @throws Exception errors
     */
    @Override
    public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
        ChildData data = event.getData();
        if(ObjectUtils.isEmpty(data)){
           log.debug("ChildData 空 type : {} Childs : {}",event.getType(),event.getInitialData());
           return;
        }
        log.info("事件监听：路径 {} 状态 {}",data.getPath(),data.getStat());
        String message = new String(data.getData());
        String path = data.getPath();
        if(!path.startsWith(getParentPath())){
            log.warn("未事件监听：path : {} message : {}",path,message);
            return;
        }
        ServerNode serverNode = mapper.readValue(message, ServerNode.class);
        int i = path.lastIndexOf("/");
        String substring = path.substring(i + 1);
        serverNode.getHosts().get(0).setSerializeId(substring);
        String parentPath = path.replace("/" + substring,"");
        List<String> paths = client.getChildren().forPath(parentPath);
        log.warn("paths {}",paths);
        String key = serverNode.getServiceName();
        switch (event.getType()) {
            case CHILD_ADDED:
                log.info("CHILD_REMOVED : {}  数据: {}",path,new String(data.getData()));
                DataServerUtil.add(key,serverNode.getHosts().get(0));
                break;
            case CHILD_REMOVED:
                log.info("CHILD_REMOVED : {}  数据: {}",path,new String(data.getData()));
                DataServerUtil.remove(key,serverNode.getHosts().get(0).getInstanceId());
                break;
            case CHILD_UPDATED:
                log.warn("update : {}  数据: {}",path,new String(data.getData()));
                DataServerUtil.update(key,serverNode.getHosts().get(0));
                break;
            default:
                break;
        }
    }


    private String getParentPath(){
       return symbol+zookeeperProperties.getRegistryPath()+symbol+zookeeperProperties.getServerName();
    }
}
